#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#include "http.h"
#include "config.h"
#include "token.h"

//成功返回access token，失败返回NULL
char *get_access_token(const char *ak, const char *sk)
{
    char* token = NULL;

    //设置URL
    char* url = "https://aip.baidubce.com/oauth/2.0/token";
    char* form = NULL;
    asprintf(&form, "grant_type=client_credentials&client_id=%s&client_secret=%s&", ak, sk);

    //发送请求报文
    size_t size = strlen(form);
    char* response = http_post(url, NULL, form, &size);
    free(form);

    if (!response)
    {
        return NULL;
    }

    //解析响应报文
    cJSON* root = cJSON_ParseWithLength(response, size);
    free(response);

    if (!root)
    {
        // 解析错误
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL)
        {
            fprintf(stderr, "Error before: %s\n", error_ptr);
        }
        return NULL;
    }

    cJSON* access_token = cJSON_GetObjectItem(root, "access_token");
    if (!access_token)
    {
        fprintf(stderr, "access_token attribute not found\n");
        cJSON_Delete(root);
        return NULL;
    }

    if (!cJSON_IsString(access_token))
    {
        fprintf(stderr, "access_token attribute format error\n");
        cJSON_Delete(root);
        return NULL;
    }

    token = strdup(access_token->valuestring);

    // 删除解析后对象占用的内存
    cJSON_Delete(root);

    return token;
}